import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query, Req } from '@nestjs/common';
import { MerchantService } from './merchant.service';
import { DtoPipe } from '../../pipe/dto/dto.pipe';
import CreateDto from './dto/create.dto';
import { MemberBelong, ReqAttrs } from '../../constant';
import { ResponseUtilService } from '@app/response-util';
import UpdateDto from './dto/update.dto';
import PageDto from './dto/page.dto';
import ResetPwdDto from './dto/resetpwd.dto';

@Controller('merchant')
export class MerchantController {
    constructor(
        private readonly service:MerchantService
    ) {}

    

    @Post('page')
    async page(@Body(new DtoPipe({skipMissingProperties : true})) dto:PageDto, @Req() req) {
        const memberId = req[ReqAttrs.MEMBER_ID]
        const result = await this.service.page(dto, memberId)

        return ResponseUtilService.successRes(result)

    }

    @Post('add')
    async add(@Body(new DtoPipe()) dto:CreateDto, @Req() req) {
        try {
            const r = await this.service.add(dto, req[ReqAttrs.MEMBER_ID], req[ReqAttrs.MERCHANT_ID])
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Put('update')
    async update(@Body(new DtoPipe()) dto:UpdateDto) {
        try {
            const r = await this.service.update(dto)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Delete('delete/:id')
    async del(@Param('id', ParseIntPipe) id:number) {
        if(id < 1) return null
        try {
            const r = await this.service.del(id)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        } 
    }

    @Put('resetpwd')
    async resetpwd(@Body(new DtoPipe()) dto:ResetPwdDto) {
        try {
            const r = await this.service.resetPwd(dto.id, dto.password)
            return r ? ResponseUtilService.successRes() : ResponseUtilService.failRes()
        } catch (error) {
            return ResponseUtilService.failRes(error.message)
        }
    }

    @Get("query")
    async queryMerchantByName(@Req() req, @Query('name') name:string) {
        console.log(req[ReqAttrs.MERCHANT_ID])
        const rows = await this.service.queryMerchantByName(name, req[ReqAttrs.MERCHANT_ID])
        return ResponseUtilService.successRes(rows)
    }
}
